package nl.han.dare2date.service.web.applyregistration.CreditcardCompany;

import nl.han.dare2date.service.web.applyregistration.model.Creditcard;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA.
 * User: Wrflohil
 * Date: 17-6-13
 * Time: 10:34
 * <element name="number" type="int"/>
 * <element name="cvc" type="int"/>
 * <element name="validThrough" type="dateTime"/>
 */
public class ExternalCreditcardValidationService{

    public boolean checkCreditCard(Creditcard cc) {

        String bankNo = ""+ cc.getNumber();
        String cvc = ""+ cc.getCvc();
        String date = "" + cc.getValidThrough();

        if(doModulo(bankNo) && doCvcCheck(bankNo, cvc) && doDate(date)) return true; else return false;
    }

    public boolean doModulo(String number) {
        int counter = 9;
        int sum = 0;
        for(char c : number.toCharArray()) {
             int i = Integer.parseInt(c+"");
            sum += (counter*i);
            counter--;
        }
        if(sum%11==0) return true; else return false;
    }

    public boolean doCvcCheck(String bankNo, String cvc) {
        String lastNo = bankNo.substring(bankNo.length()-3, bankNo.length());
        if(lastNo.equals(cvc)) return true; else return false;
    }

    public boolean doDate(String date) {
        String[] dateSplit = date.split("T");
        Date date1 = null;
        Date date2 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");

        String todayWithZeroTime = sdf.format(date2);
        try {
            date1 = new SimpleDateFormat("yyyy-M-d", Locale.ENGLISH).parse(dateSplit[0]);
            date2 = new SimpleDateFormat("yyyy-M-d", Locale.ENGLISH).parse(todayWithZeroTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(date1.after(date2)) return true; else return false;
    }
}
